package com.iweb.xt.sso.domain.repository;

import com.iweb.xt.common.constants.RedisKey;
import com.iweb.xt.common.wx.WxOpenConfig;
import com.iweb.xt.sso.domain.LoginDomain;
import com.iweb.xt.sso.domain.UserDomain;
import com.iweb.xt.sso.model.param.login.LoginParam;
import com.iweb.xt.sso.model.param.user.UserParam;
import me.chanjar.weixin.mp.api.WxMpService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LoginDomainRepository {
    @Autowired
    public WxMpService wxMpService;
    @Autowired
    public WxOpenConfig wxOpenConfig;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private UserDomainRepository userDomainRepository;

    public LoginDomain createLoginDomain(LoginParam loginParam) {
        return new LoginDomain(this,loginParam);
    }

    public String buildUrl() {
        //        构建微信登陆的二维码
//        构建state 给微信 但是微信回调的时候  还会给我
//        可以校验两次的state 是否一致 判断是否发生了csrf攻击
//        使用时间格式
        String csrfKey =new DateTime().toString("yyyyMMddHHmmss");
        //        这个key要保存在redis
        redisTemplate.opsForValue().set(RedisKey.WX_STATE_KEY+csrfKey,"",2, TimeUnit.MINUTES);
//        构建url
        return wxMpService.buildQrConnectUrl(wxOpenConfig.getRedirectUrl(), wxOpenConfig.getScope(), csrfKey);


////        加密一下
//        String state = DigestUtils.md5Hex(time);
////        构建二维码
//        String url=wxMpService.buildQrConnectUrl(wxOpenConfig.getRedirectUrl(), wxOpenConfig.getScope(), state);
//        return CallResult.success(url);
    }

    public boolean chechState(String state) {
      return   redisTemplate.hasKey(RedisKey.WX_STATE_KEY+state);
    }
    public UserDomain createUserDomain(UserParam userParam){
        return userDomainRepository.createUserDomain(userParam);
    }
}
